import requests
import tempfile
import os
import re
from fontTools.ttLib import TTFont


class PddFont:
    ttf_url: str = None
    file: str = None
    fontMap = {
        '100000010000001000010000100000010000001000010000': '0',
        '11000011111': '1',
        '10000100001001010000111100001000010000100001': '2',
        '10100011000010011000010000100110010000100001100001001000010101': '3',
        '111111111111111': '4',
        '11110010000000001000011000010000100001001111': '5',
        '10000100001000010000100100001000010000100001001100001001': '6',
        '111100001100001': '7',
        '100001000010000100100100100001000010010010000100001000010010010000': '8',
        '100001000010000100001000010010000100001000010011001001': '9',
    }
    dbMap = {}

    # ttf下载
    def ttfFile_download(self):
        if self.ttf_url is None:
            raise ValueError
        response = requests.get(self.ttf_url).content
        file = tempfile.NamedTemporaryFile().name
        with open(file, 'wb') as f:
            f.write(response)
        self.file = file
        self.ttfFile_tranF()

    def ttf_save(self, content):
        file = tempfile.NamedTemporaryFile().name
        with open(file, 'wb') as f:
            f.write(content)
        self.file = file
        self.ttfFile_tranF()

    # ttf 转换 xml
    def ttfFile_tranF(self):
        if self.file is None:
            self.ttfFile_download()
        ttf_file = TTFont(self.file)
        ttf_file.saveXML(self.file)

    # 提取特征码
    def extract_feature(self):
        if self.file is None:
            self.ttfFile_download()
        with open(self.file, 'r') as f:
            content = f.read()
        arr = re.findall('<TTGlyph name="uni.*?</TTGlyph>', content, re.S)
        for row in arr:
            name = re.findall('name="uni(.*?)"', row, re.S)[0]
            x_arr = re.findall(r'<pt.*?on="(.*?)"', row)
            x_path = ''.join(x_arr)
            self.dbMap[name.lower()] = x_path

    # fontMap(本地) dbMap(下载) 对比替换
    def comparison(self):
        dbMap = self.dbMap
        if dbMap == {}:
            self.extract_feature()
        for name in self.dbMap:  # map_1 = {name*10: signature_code}
            s = {'key': None, 'diff': 20}
            target = self.dbMap[name]  # target = signature_code
            # fontMap
            for row in self.fontMap:
                # 长度差距过大 则直接跳过当前对比
                if len(row) > len(target) + 8 or len(row) < len(target) - 8:
                    continue
                diff = 0  # 初始化对比值
                # 不相同 diff+1
                for i in range(min(len(target), len(row))):
                    if target[i] != row[i]:
                        diff += 1
                # 判断 取差距最小的
                if diff < s['diff']:
                    s = {'key': row, 'diff': diff}
            self.dbMap[name] = self.fontMap[s['key']]

    def atob(self, keys):
        decode_keys = ''
        for key in keys:
            if key in ['.']:
                decode_keys += key
                continue
            elif key in [',', '%']:
                continue
            code = key.encode('unicode_escape').decode('utf8')
            code = re.sub(r'\\u', '', code)
            decode_keys += self.dbMap[code]
        return decode_keys

    def __del__(self):
        try:
            os.remove(self.file)
        except:
            pass


if __name__ == '__main__':
    font_test = PddFont()
    font_test.ttf_url = 'https://pfile.pddpic.com/webspider-sdk-api/14e04abd7dca4d2eacd81043b4977d8a-fd714bed37464e6abdbf2229263c4768.ttf'
    font_test.comparison()
    print(font_test.dbMap)
    print(font_test.atob(''))